package linearlist;

import javax.xml.soap.Node;
import java.util.Iterator;

/**
 * @Author Zhouchb
 * @Create 2021-10-2021/10/27 :13:59
 * @Description
 */
public class LinkList<T> implements Iterable{
    private Node head;//记录首节点
    private int N; //记录链表长度

    //创建LinkList对象
    public LinkList() {
        head = new Node(null, null);
        int N = 0;
    }



    //节点类
    private class Node<T> {
        //存储数据
        T item;
        //下一个节点
        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }

    }

    //置空线性表
    public void clear() {
        head.next = null;
        this.N = 0;
    }

    //判断线性表是否为空，是返回true
    public boolean isEmpty() {
        return this.N == 0;
    }

    //获取线性表中元素的个数
    public int length() {
        return N;
    }

    //读取并返回线性表中的第i个元素的值
    public T get(int i) {
        Node node = head.next;
        for (int j = 0; j < i; j++) {
            node = node.next;
        }
        T item = (T) node.item;
        return item;
    }

    //往线性表中添加一个元素
    public void insert(T t) {
        Node node = head;
        for (; node.next != null; ) {
            node = node.next;
        }
        Node newNode = new Node(t, null);
        node.next = newNode;
        N++;
    }

    //在线性表第i个元素之前插入一个元素
    public void insert(int i, T t) {
        Node node = head;
        for (int j = 0; j <= i; j++) {
            node = node.next;
        }
        Node cur = node.next;
        Node newnode = new Node(t, cur);
        node.next = newnode;
        N++;
    }

    //删除并返回线性表中第i个元素
    public T remove(int i) {
        Node node = head.next;
        for (int j = 0; j < i - 1; j++) {
            node = node.next;
        }
        Node del = node.next;
        node.next = del.next;
        T t = (T) del.item;
        N--;
        return t;
    }

    //查找元素t在链表中第一次出现的位置
    public int indexOf(T t) {
        Node node = head.next;
        for (int j = 0; node.next != null; j++) {
            if (node.item .equals(t)) {
                return j;
            }
            node = node.next;
        }
        return -1;
    }

    @Override
    public Iterator iterator() {
        return new GetIterator();
    }
    class GetIterator implements Iterator{
        private LinkList.Node n;
        public GetIterator(){
            this.n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }
}
